<!--
  @author: cqz
  @desc: 去除重复记录
  @params:
  @date: 2020-12-22
-->
<template>
  <div class="">
    <el-form ref="unique" :model="unique" label-width="140px">
      <el-form-item label="步骤名称" prop="name">
        <el-input v-model="unique.name"></el-input>
      </el-form-item>
      <div style="margin-top:20px;margin-bottom:5px"><span>去除重复记录的字段</span></div>
      <el-table :data="unique.fields" border style="width: 100%;" size="mini" height="170">
        <el-table-column label="操作" width="80" :resizable=false>
          <template slot-scope="scope">
            <div class="optionStyle">
              <el-button
                type="text"
                @click="removeObj(scope.$index)"
                size="mini">移除
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column property="name" label="字段名称">
          <template slot-scope="scope">
            <el-select v-model="scope.row.column_name" style="width: 100%;" size="mini" @focus="getFiledsOption">
              <el-option
                v-for="item in streamFields"
                :key="item.name"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex">
        <el-button class="el-table-add-row"  @click="addObj" icon="el-icon-plus"> 添加</el-button>
        <div style="width: 20px"></div>
        <el-button  class="el-table-add-row" @click="getField" icon="el-icon-thumb">获取字段</el-button>
      </el-row>
    </el-form>
    <div class="el-dialog__footer">
      <span class="dialog-footer">
         <el-button
           icon="el-icon-back"
           @click="cancel">取消
         </el-button>
        <el-button
          type="primary" icon="el-icon-check"
          @click="handleSaveData()">确定
        </el-button>
      </span>
    </div>
  </div>
</template>

<script>
import API from '../../../../../api/index'
import mxgraph from '../../../../../graph/VueMxGraphLoader'
import xmlToFlinkJSON from '../../../../../utils/xmlToFlinkJson'
import {flinkInputFields} from "../../../../../api/modules/trans";
/* eslint-disable no-undef */
/* eslint-disable no-new-object */
/* eslint-disable new-cap */
const {
  mxUtils,
  mxCodec
} = mxgraph
export default {
  name: 'unique',
  props: {
    name: String
  },
  data () {
    return {
      count_rows: true,
      graph: null,
      reject_duplicate_row: true,
      streamFields: [],
      flagOptions: [{code: 'Y', name: '是'}, {code: 'N', name: '否'}],
      unique: {
        type: 'UniqueRowsByHashSet',
        name: '', // 步骤名称
        count_rows: 'N', // 是否增加计数到输出
        count_field: '', // 计数器字段
        reject_duplicate_row: 'Y', // 是否重定向重复记录
        error_description: '', // 错误描述
        fields: []
      },
      tempUnique: null,
      temp: {
        type: 'UniqueRowsByHashSet',
        name: '', // 步骤名称
        count_rows: 'N', // 是否增加计数到输出
        count_field: '', // 计数器字段
        reject_duplicate_row: 'Y', // 是否重定向重复记录
        error_description: '', // 错误描述
        fields: []
      }
    }
  },
  watch: {
    unique (data) {
      this.count_rows = data.count_rows === 'N'
      this.reject_duplicate_row = data.reject_duplicate_row === 'N'
    }
  },
  methods: {
    loadData (data) {
      if (data) {
        this.$forceUpdate()
        this.unique = Object.assign({}, data)
        this.tempUnique = JSON.parse(JSON.stringify(data))
      }
    },
    // 保存表单数据
    handleSaveData () {
      if (this.unique.name) {
        this.$emit('savePluginData', this.unique)
      } else {
        this.$message({
          message: '步骤名称必填',
          type: 'warning'
        })
      }
    },
    cancel () {
      if (this.tempUnique) {
        this.saveTempPluginData(this.tempUnique)
      } else {
        let tempdata = JSON.parse(JSON.stringify(this.temp))
        tempdata['name'] = this.unique.name
        this.saveTempPluginData(tempdata)
      }
      this.$emit('cancel')
    },
    setGraph (val) {
      this.graph = val
    },
    // 重置表单数据
    resetFormData (stepname) {
      this.$forceUpdate()
      this.$refs['unique'].resetFields()
      this.unique = JSON.parse(JSON.stringify(this.temp))
      this.unique['name'] = stepname
    },
    async getFiledsOption () {
      if (this.streamFields.length === 0) {
        const streamFields = await this.getStreamField()
        if (streamFields) {
          this.$set(this, 'streamFields', streamFields.data.data.data.fields)
        }
      }
    },
    countRowsChange (val) {
      this.count_rows = val === 'N'
    },
    rejectDuplicateRowChange (val) {
      this.reject_duplicate_row = val === 'N'
    },
    async getField () {
      const self = this
      let streamFields = await this.getStreamField()
      var tempFileds = []
      if (streamFields.length !== 0) {
        streamFields.data.data.data.fields.forEach(element => {
          let obj = {}
          obj.column_name = element.name
          tempFileds.push(obj)
        })
      }
      self.$set(self.unique, 'fields', tempFileds)
    },
    async getStreamField () {
      const value = await this.getXml()
      if (this.unique.name) {
        return API.trans.flinkInputFields(value, {'stepName': this.unique.name})
      }
    },
    getXml () {
      this.saveTempPluginData(this.unique)
      const graph = this.graph
      const enc = new mxCodec(mxUtils.createXmlDocument())
      const node = enc.encode(graph.getModel())
      // const value = mxUtils.getPrettyXml(node)
      let queryParJson = xmlToFlinkJSON.xmlToFlinkModels(node)
      queryParJson.models.model["step_name"] = this.unique.name
      queryParJson.models.model["step_type"] = "uniqueRowsByHashSet"
      return queryParJson
    },
    async getStreamFieldOptions () {
      const result = this.getStreamField()
      this.$refs['tableField'].setOptions(result)
    },
    saveTempPluginData (formData) {
      this.$emit('saveTempPluginData', formData)
    },
    removeObj (index) {
      this.unique.fields.splice(index, 1)
    },
    async addObj () {
      this.unique.fields.push({})
      this.$nextTick(() => {
        let container = this.$el.querySelector('.el-table__body-wrapper')
        container.scrollTop = container.scrollHeight
      })
      if (this.streamFields.length === 0) {
        const streamFields = await this.getStreamField()
        if (streamFields) {
          this.$set(this, 'streamFields', streamFields.data)
        }
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.el-form-item {
  margin-bottom: 10px !important;
}
.el-dialog__footer {
  margin-top: 50px;
}
</style>
